package com.xbongbong.pro.message.model.impl;

import com.xbongbong.message.domain.dao.PushDao;
import com.xbongbong.message.domain.entity.PushEntity;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.CommentUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.message.enums.PushTypeEnum;
import com.xbongbong.pro.message.enums.RefEntityEnum;
import com.xbongbong.pro.message.model.PushLinkModel;
import com.xbongbong.pro.message.model.PushModel;
import com.xbongbong.saas.constant.ParameterConstant;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * Description: PushModel 实现
 * @author 魏荣杰
 * @date 2019/1/6 1:09
 * @version v1.0
 * @since v1.0
 */
@Service("pushModel")
public class PushModelImpl implements PushModel {

    @Resource
    private PushDao pushDao;
    @Resource
    private PushLinkModel pushLinkModel;

    @Override
    public Integer insert(PushEntity entity) throws XbbException {
        Long now = DateTimeUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);

        return pushDao.insert(entity);
    }

    @Override
    public Integer update(PushEntity entity) throws XbbException{
        entity.setUpdateTime(DateTimeUtil.getInt());

        return pushDao.update(entity);
    }

    @Override
    public List<PushEntity> findEntitys(Map<String, Object> param) {
        return pushDao.findEntitys(param);
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return pushDao.getEntitysCount(param);
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return null;
    }


    @Override
    public void insertBatch(List<PushEntity> pushList) {
        for (PushEntity push : pushList) {
            checkRefArray(push);
        }
        pushDao.insertBatch(pushList);
    }



    @Override
    public Integer save(PushEntity entity) {
        //message insert的复杂逻辑提到service，这边只做单纯的保存
        Long now = DateTimeUtil.getInt();
        entity.setUpdateTime(now);
        if (entity.getId() == null || Objects.equals(0L, entity.getId())) {
            entity.setAddTime(now);
            return pushDao.insert(entity);
        }
        return pushDao.update(entity);
    }

    /**
     * 如果消息未设置对象 id 列表则赋初始值
     *
     * @param push 消息
     */
    private void checkRefArray(PushEntity push) {
        if (StringUtil.isEmpty(push.getRefArray())) {
            if (push.getRefId() == null) {
                push.setRefArray("[]");
            } else {
                push.setRefArray("[" + push.getRefId() + "]");
            }
        }
    }

    @Override
    public Integer deleteByKey(Integer key, String corpid) {
        return pushDao.deleteByKey(key, corpid);
    }

    @Override
    public PushEntity getByKey(Integer key, String corpid) {
        return pushDao.getByKey(key, corpid);
    }

    @Override
    public Map<Long, Integer> getRemindMap(List<Long> refIdIn,
                                              String corpid, String userId, Integer refEntity) {
        Map<Long, Integer> focusMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<String, Object> params = new HashMap<>(16);
        params.put("corpid", corpid);
        params.put("userId", userId);
        params.put("columns", "ref_id");
        params.put("refIdIn", refIdIn);
        params.put("isRemind", 1);
        params.put("startPushTime", DateUtil.getInt());
        params.put("refEntity", refEntity);
        params.put("del", 0);
        List<PushEntity> list = findEntitys(params);
        for (PushEntity entity : list) {
            focusMap.put(entity.getRefId(), 1);
        }
        return focusMap;
    }

    @Override
    public Integer deleteByIdIn(List<Long> pushIds, String corpid) throws XbbException {
        return pushDao.deleteByIdIn(pushIds, corpid);
    }

    /**
     * 根据refId(关联的业务的具体表中的数据)去批量删除tb_push消息表中的消息
     *
     * @param dataIdList refId列表
     * @param corpid
     * @return
     */
    @Override
    public Integer deleteByRefIds(List<Long> dataIdList, String corpid) {
        return pushDao.deleteByRefIds(dataIdList,corpid);
    }

    @Override
    public List<Long> getAlreadyProduceId(String corpid, Long todayInt, Long todayEndInt, Integer subCode, Integer type) {
        return pushDao.getAlreadyProduceId(corpid, todayInt, todayEndInt, subCode ,type);
    }

    @Override
    public List<PushEntity> getPushNotify(Collection<Long> dataIdIn, String corpid, Integer businessType, Collection<Long> pushNotifyList) {
        List<PushEntity> pushEntityList = new ArrayList<>();
        if (CollectionsUtil.isEmpty(dataIdIn)) {
            return pushEntityList;
        }
        Map<String, Object> param = pushNotifyParam(dataIdIn, corpid, businessType, DateUtil.getInt(), null);
        pushEntityList = findEntitys(param);
        for (PushEntity pushEntity : pushEntityList) {
            pushNotifyList.add(pushEntity.getRefId());
        }
        return pushEntityList;
    }

    @Override
    public Collection<Long> getPushNotify(Collection<Long> dataIdIn, String corpid, Integer businessType) {
        Set<Long> pushNotifyList = new HashSet<>();
        if (CollectionsUtil.isEmpty(dataIdIn)) {
            return pushNotifyList;
        }
        List<PushEntity> pushEntityList = findEntitys(pushNotifyParam(dataIdIn, corpid, businessType, DateUtil.getInt(), null));
        for (PushEntity pushEntity : pushEntityList) {
            pushNotifyList.add(pushEntity.getRefId());
        }
        return pushNotifyList;
    }

    @Override
    public Integer getPushCount(Long dataId, String corpid, Integer businessType, Integer startTime, Integer endTime) {
        Map<String, Object> param = pushNotifyParam(Collections.singleton(dataId), corpid, businessType, startTime, endTime);
        return getEntitysCount(param);
    }

    @Override
    public Map<String, Object> pushNotifyParam(Collection<Long> dataIdIn, String corpid, Integer businessType, Integer startTime, Integer endTime) {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("refIdIn", dataIdIn);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put(ParameterConstant.CORPID, corpid);
        //塞入开始、结束时间，如果为空则不作为条件
        CommentUtil.addToMap(param, "startPushTime", startTime);
        CommentUtil.addToMap(param, "endPushTime", endTime);
        param.put("isRemind", 1);
        RefEntityEnum refEntityEnum = RefEntityEnum.getByCode(businessType);
        param.put("refEntity", refEntityEnum.getCode());
        PushTypeEnum pushTypeEnum = PushTypeEnum.getByCode(businessType);
        param.put("type", pushTypeEnum.getCode());
        param.put("subType", pushTypeEnum.getSubCode());
        return param;
    }

    @Override
    public void deletePushNotify(List<Long> refIdIn, String corpid, Integer businessType) throws XbbException {
        List<Long> notifyIdList = new ArrayList<>();
        List<PushEntity> pushNotifyList = getPushNotify(refIdIn, corpid, businessType, notifyIdList);
        if (!pushNotifyList.isEmpty()) {
            List<Long> pushIds = new ArrayList<>();
            pushNotifyList.forEach(pushEntity -> pushIds.add(pushEntity.getId()));
            if (!pushIds.isEmpty()) {
                deleteByIdIn(pushIds, corpid);
                pushLinkModel.deleteByPushIdIn(pushIds, corpid);
            }
        }
    }
}

